package com.atguigu.gulimall.search.Service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.es.SkuEsModel;
import com.atguigu.gulimall.search.Service.ProductSaveService;
import com.atguigu.gulimall.search.config.GulimallElasitcSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jingchun
 * @create 2024-07-09 21:36
 */

@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

	@Autowired
	RestHighLevelClient esRestClient;

	@Override
	public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
		//1.建立好映射关系

		//2.给ES保存数据 bulk()
		BulkRequest bulkRequest = new BulkRequest(); //批量请求
		for(SkuEsModel skuEsModel:skuEsModels){
		//构造保存请求
			IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);//索引
			indexRequest.id(skuEsModel.getSkuId().toString());//id
			String jsonString = JSON.toJSONString(skuEsModel);//转成json
			indexRequest.source(jsonString, XContentType.JSON); //构造保存请求
			bulkRequest.add(indexRequest); //添加到批量请求中
		}
		BulkResponse bulk = esRestClient.bulk(bulkRequest, GulimallElasitcSearchConfig.COMMON_OPTIONS);//执行批量保存

	//	TODO 如果批量错误
		boolean hasFailures = bulk.hasFailures();
		List<String> collect = Arrays.asList(bulk.getItems()).stream()  .map(item -> {
			return item.getId();
		}).collect(Collectors.toList());

		log.info("商品上架完成：{}",collect);

		return hasFailures;
	}
}
